package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.PageInfo;
import com.tanhua.dubbo.server.pojo.Users;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/2/23 20:20
 * @version: 0.0.1
 * @modified By:
 */
@Service(version = "1.0.0")
public class UsersApiImpl implements UsersApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveUsers(Users users) {
        if(null==users.getUserId()||null==users.getFriendId()){
            return null;
        }
        //检测该好友关系是否存在
        Query query=Query.query(Criteria.where("userId").is(users.getUserId())
                .and("friendId").is(users.getFriendId()));
        Users oldUsers = this.mongoTemplate.findOne(query, Users.class);
        if(null!=oldUsers){
            return null;
        }
        users.setId(ObjectId.get());
        users.setDate(System.currentTimeMillis());
        //注册我与好友的关系
        this.mongoTemplate.save(users);
        return users.getId().toHexString();
    }
    /**
     * @description 根据用户id查询Users列表(分页查询)
     * @author
     * @date
     * @param
     *@return
     */
    @Override
    public PageInfo<Users> queryUsersList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Users>pageInfo=new PageInfo<>();
        pageInfo.setTotal(0); //不提供总数
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        PageRequest pageRequest=PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc("created")));
        Query query=Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Users> usersList = this.mongoTemplate.find(query, Users.class);
        pageInfo.setRecords(usersList);
        return pageInfo;
    }
    /**
     * @description 根据用户id查询Users列表
     * @author
     * @date
     * @param
     *@return
     */
    @Override
    public List<Users> queryAllUsersList(Long userId) {
        Query query=Query.query(Criteria.where("userId").is(userId));
        List<Users> usersList = this.mongoTemplate.find(query, Users.class);
        return usersList;
    }
}
